package com.dms.service.impl;

import com.dms.common.ResponseCode;
import com.dms.common.ServerResponse;
import com.dms.dao.ApplyMapper;
import com.dms.dao.FileMapper;
import com.dms.pojo.Apply;
import com.dms.pojo.File;
import com.dms.service.IFileService;
import com.dms.util.DateTimeUtil;
import com.dms.util.FTPUtil;
import com.dms.vo.FileDetailVo;
import com.dms.vo.FileListVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import static com.dms.common.Const.UPLOAD_FAIL;

@Service("iFileService")
public class FileServiceImpl implements IFileService {

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private ApplyMapper applyMapper;

    private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    /**
     * 保存文件或者更新文件
     *
     * @param file
     * @return
     */
    public ServerResponse saveOrUpdateFile(File file) {
        if (file != null) {
            if (file.getId() != null) {
                int rowCount = fileMapper.updateByPrimaryKey(file);
                if ((rowCount > 0)) {
                    return ServerResponse.createBySuccess("更新成功！");
                }
                return ServerResponse.createByErrorMessage("更新失败！");
            } else {
                int rowCount = fileMapper.insert(file);
                if (rowCount > 0) {
                    return ServerResponse.createBySuccess("新增文件成功！");
                }
                return ServerResponse.createByErrorMessage("新增失败！");
            }
        }
        return ServerResponse.createByErrorMessage("新增或者更新参数不正确");
    }


    public ServerResponse<String> setFileStatus(Integer fileId, Integer status) {
        if (fileId == null || status == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

        File file = new File();
        file.setId(fileId);
        file.setLevel(status);
        int rowCount = fileMapper.updateByPrimaryKeySelective(file);
        if (rowCount > 0) {
            return ServerResponse.createBySuccess("修改文件权限成功");
        }
        return ServerResponse.createByErrorMessage("修改文件权限失败");
    }

    public ServerResponse<FileDetailVo> manageFileDetail(Integer fileId) {
        if (fileId == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        File file = fileMapper.selectByPrimaryKey(fileId);
        if (file == null) {
            return ServerResponse.createByErrorMessage("文件已经删除");
        }

        //返回ＶＯ对象
        FileDetailVo fileDetailVo = assembleFileDetailVo(file);

        logger.info("tpye:" + fileDetailVo.getType());
        logger.info("id:" + fileDetailVo.getCategoryId());
        return ServerResponse.createBySuccess(fileDetailVo);
    }

    /**
     * 封装FileDetailVo
     *
     * @param file
     * @return
     */
    public FileDetailVo assembleFileDetailVo(File file) {
        FileDetailVo fileDetailVo = new FileDetailVo();
        fileDetailVo.setId(file.getId());
        fileDetailVo.setAddress(file.getAddress());
        fileDetailVo.setCategoryId(file.getCategoryId());
        fileDetailVo.setType(file.getType());
        fileDetailVo.setName(file.getName());
        fileDetailVo.setLevel(file.getLevel());
        fileDetailVo.setUploader(file.getUploader());
        //分类
//        fileDetailVo.setCategoryId();

        fileDetailVo.setCreateTime(DateTimeUtil.dateToStr(file.getCreateTime()));
        fileDetailVo.setUpdateTime(DateTimeUtil.dateToStr(file.getUpdateTime()));

        return fileDetailVo;
    }

    /**
     * 得到文件列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public ServerResponse getFileList(int pageNum, int pageSize) {
        //startPage ---start
        //填充自己的ｓｑｌ查询逻辑
        //pageHelper--收尾
        PageHelper.startPage(pageNum, pageSize);
        List<File> fileList = fileMapper.selectList();

        List<FileListVo> fileListVoList = Lists.newArrayList();
        for (File fileItem : fileList) {
            FileListVo fileListVo = assembleFileList(fileItem);
            fileListVoList.add(fileListVo);
        }
        PageInfo pageResult = new PageInfo(fileList);

        pageResult.setList(fileListVoList);
        return ServerResponse.createBySuccess(pageResult);

    }

    /**
     * 封装FileListVo
     *
     * @return
     */
    public FileListVo assembleFileList(File file) {
        FileListVo fileListVo = new FileListVo();
        fileListVo.setId(file.getId());
        fileListVo.setName(file.getName());
        fileListVo.setCategoryId(file.getCategoryId());
        fileListVo.setType(file.getType());
        fileListVo.setUploader(file.getUploader());
//        fileListVo.setUpdateTime(DateTimeUtil.dateToStr(file.getUpdateTime()));
        return fileListVo;
    }


    /**
     * 查询文件
     *
     * @param fileName
     * @param pageNum
     * @param pageSize
     * @return
     */
    public ServerResponse<PageInfo> searchFile(String fileName, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        List<File> fileList = null;
        if (StringUtils.isEmpty(fileName)) {
            fileList = fileMapper.selectList();
        } else {
            fileName = new StringBuilder().append("%").append(fileName).append("%").toString();
            fileList = fileMapper.selectByFileName(fileName);
        }

        List<FileListVo> fileListVoList = Lists.newArrayList();
        for (File fileItem : fileList) {
            FileListVo fileListVo = assembleFileList(fileItem);
            fileListVoList.add(fileListVo);
        }

        PageInfo pageResult = new PageInfo(fileList);

        pageResult.setList(fileListVoList);
        return ServerResponse.createBySuccess(pageResult);
    }

    /**
     * 文件上传
     *
     * @param file
     * @param path
     * @return
     */
    public String upload(MultipartFile file, String path, String uploadFileName) {

        java.io.File fileDir = new java.io.File(path);
        if (!fileDir.exists()) {
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        java.io.File targetFile = new java.io.File(path, uploadFileName);

        try {
            file.transferTo(targetFile);
            //文件已经上传成功了
            if (!FTPUtil.uploadFile(Lists.newArrayList(targetFile))) {
                return UPLOAD_FAIL;
            }

            //写入申请列表
//            Apply apply = new Apply();
//            apply.setStatus(0);
//            apply.setName(fileStartName);
//            apply.setType(fileExtensionName);
//            apply.setUploader("admin");
//            apply.setAddress(uploadFileName);
//            applyMapper.insert(apply);

            //已经上传到ftp服务器上
            targetFile.delete();
        } catch (IOException e) {
            logger.error("上传文件异常", e);
            return null;
        }

        return targetFile.getName();
    }

    /**
     * 文件下载
     *
     * @param localPath
     * @param fileName
     * @return
     */
    public boolean download(String localPath, String fileName, String fileNewName) {
        java.io.File fileDir = new java.io.File(localPath);
        if (!fileDir.exists()) {
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        try {
            FTPUtil.downFile(localPath, fileName, fileNewName);
        } catch (IOException e) {

            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 文件移动
     *
     * @param address
     * @return
     */
    public String moveFie(String address) {
        try {
            FTPUtil.moveFile(address);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public ServerResponse<File> SaveFilesData(File file) {
        int resultCount = fileMapper.insert(file);
        if (resultCount == 0) {
            return ServerResponse.createByErrorMessage("添加失败");
        }
        return ServerResponse.createBySuccessMessage("添加成功");
    }


}
